package com.example.librarymanagement.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.librarymanagement.dto.reader.ReaderAddDto;
import com.example.librarymanagement.dto.reader.ReaderListDto;
import com.example.librarymanagement.dto.reader.ReaderUpdDto;
import com.example.librarymanagement.entity.Reader;
import com.example.librarymanagement.entity.User;
import com.example.librarymanagement.entity.UserReader;
import com.example.librarymanagement.result.ResultCode;
import com.example.librarymanagement.service.IReaderService;
import com.example.librarymanagement.service.IUserReaderService;
import com.example.librarymanagement.service.IUserService;
import com.example.librarymanagement.util.CheckEntityUtil;
import com.example.librarymanagement.vo.ReaderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author zhb
 */
@Api(tags = "读者模块")
@RestController
@RequestMapping("/reader")
public class ReaderController extends BaseController {

    @GetMapping
    @ApiOperation(value = "查询读者列表")
    @PreAuthorize("hasAuthority('reader:manage:list')")
    public IPage<ReaderVo> getReaderList(@Validated ReaderListDto readerListDto) {
        return readerService.getReaderList(readerListDto);
    }

    @GetMapping("/info/{id}")
    @ApiOperation(value = "查询读者信息")
    @PreAuthorize("hasAuthority('reader:manage:list')")
    public ReaderVo getReaderInfo(@PathVariable Integer id) {
        Reader reader = readerService.getById(id);
        ReaderVo readerVo = new ReaderVo();
        readerVo.setId(reader.getId());
        readerVo.setName(reader.getName());
        readerVo.setBirthday(reader.getBirthday());
        readerVo.setCreateTime(reader.getCreateTime());
        readerVo.setSex(reader.getSex());
        readerVo.setReturnCount(reader.getReturnCount());
        readerVo.setBorrowCount(reader.getBorrowCount());
        readerVo.setIdCard(reader.getIdCard());
        readerVo.setAffiliatedUnit(reader.getAffiliatedUnit());
        UserReader userReader = userReaderService.getOne(new QueryWrapper<UserReader>().eq("reader_id", id));
        User user = userService.getById(userReader.getUserId());
        readerVo.setUserId(user.getId());
        return readerVo;
    }

    @PostMapping
    @ApiOperation(value = "增加读者信息")
    @PreAuthorize("hasAuthority('reader:manage:save')")
    public void addReader(@Validated @RequestBody ReaderAddDto readerAddDto) {
        User user = CheckEntityUtil.isNullById(readerAddDto.getUserId(), userService, ResultCode.USER_ACCOUNT_NOT_EXIST);
        CheckEntityUtil.isNotNullByColumnEq("user_id", user.getId(), userReaderService, ResultCode.USER_READER_EXIST);

        Reader reader = new Reader();
        readerAddDto.convertToEntity(reader);
        reader.setCreateTime(new Timestamp(System.currentTimeMillis()));
        reader = readerService.addReader(reader);
        UserReader userReader = new UserReader();
        userReader.setUserId(user.getId());
        userReader.setReaderId(reader.getId());
        userReaderService.save(userReader);
    }

    @PutMapping
    @ApiOperation(value = "修改读者信息")
    @PreAuthorize("hasAuthority('reader:manage:update')")
    public void updReader(@Validated @RequestBody ReaderUpdDto readerUpdDto) {
        Reader reader = CheckEntityUtil.isNullById(readerUpdDto.getId(), readerService, ResultCode.READER_NOT_EXIST);
        CheckEntityUtil.isNullById(readerUpdDto.getUserId(), userService, ResultCode.READER_NOT_EXIST);
        if (readerUpdDto.getUserId() != null) {
            CheckEntityUtil.isNotNullByColumnEq("user_id",readerUpdDto.getUserId(), userReaderService, ResultCode.USER_READER_EXIST);
            UserReader userReader = userReaderService.getOne(new QueryWrapper<UserReader>().eq("reader_id",reader.getId()));
            userReader.setUserId(readerUpdDto.getUserId());
            userReaderService.updateById(userReader);
        }
        readerUpdDto.convertToEntity(reader);
        readerService.updateById(reader);
    }

    @DeleteMapping
    @Transactional(rollbackFor = {Exception.class})
    @ApiOperation(value = "禁用读者信息")
    @PreAuthorize("hasAuthority('reader:manage:delete')")
    public void delReader(String ids) {
        List<Integer> readIds = Arrays.asList(Convert.toIntArray(ids));
        readerService.removeByIds(readIds);
        userReaderService.remove(new QueryWrapper<UserReader>().in("reader_id", readIds));
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // CustomDateEditor为自定义日期编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
